import myConfig from "./myConfig";
import {
	getToken,
	saveUserToken
} from "./localData.js";

export default {
	send(options) {
		uni.showLoading({
			title: '加载中'
		});

		options.url = myConfig.uni_app_web_api_url + '' + options.url;
		options.method = options.method || "GET";
		options.header = options.header || {};
		options.header.eulb = '';
		if (options.method == "post" && options.header['Content-Type'] == undefined) {
			options.header['Content-Type'] = 'application/x-www-form-urlencoded';
		}
		// get请求映射params参数
		if (options.method === 'get' && options.params) {
			let url = options.url + '?' + this.tansParams(options.params);
			url = url.slice(0, -1);
			options.params = {};
			options.url = url;
		}
		let token = getToken();
		if (token) {
			options.header.token = token
		}
		return new Promise((resolve, reject) => {
			uni.request(options).then(data => {
				uni.hideLoading();
				let error = data.errmsg
				let res = data.data
				if (error != null) {
					reject(error);
				} else {
					if (res.statusCode == 455) {
						uni.showModal({
							title: '错误信息',
							content: "系统繁忙，请稍后再试！",
							showCancel: false,
							confirmText: "知道了",
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								}
							}
						});
						reject(res.data);
						return;
					}
					if (res.data && res.data.token) {
						saveUserToken(res.data.token);
					}
					if (res.result === 0) {
						resolve(res.data);
					} else {
						if (res.result === 1) {
							uni.showModal({
								title: '错误信息',
								content: res.errmsg,
								showCancel: false,
								confirmText: "知道了",
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
									}
								}
							});
						}
						reject(res);
					}
				}
			});
		});
	},
	tansParams(params) {
	  let result = ''
	  for (const propName of Object.keys(params)) {
	    const value = params[propName];
	    var part = encodeURIComponent(propName) + "=";
	    if (value !== null && typeof (value) !== "undefined") {
	      if (typeof value === 'object') {
	        for (const key of Object.keys(value)) {
	          if (value[key] !== null && typeof (value[key]) !== 'undefined') {
	            let params = propName + '[' + key + ']';
	            var subPart = encodeURIComponent(params) + "=";
	            result += subPart + encodeURIComponent(value[key]) + "&";
	          }
	        }
	      } else {
	        result += part + encodeURIComponent(value) + "&";
	      }
	    }
	  }
	  return result
	},
	
};